package com.ejlchina.tool.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.ItemHeadDeviceRadioBinding
import com.ejlchina.tool.bean.BleDeviceBean

@SuppressLint("NotifyDataSetChanged")
class DeviceAdapterRadioOffline(
    private val dataList: List<BleDeviceBean>,
    private val itemClick: (BleDeviceBean) -> Unit
) : RecyclerView.Adapter<DeviceAdapterRadioOffline.ItemHeadDeviceRadioViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHeadDeviceRadioViewHolder {
        val binding = ItemHeadDeviceRadioBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ItemHeadDeviceRadioViewHolder(binding, itemClick)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: ItemHeadDeviceRadioViewHolder, position: Int) {
        holder.bind(dataList[position], position)
    }

    fun getSelectDevice() = dataList.filter { it.isSelect }[0]

    inner class ItemHeadDeviceRadioViewHolder(private val binding: ItemHeadDeviceRadioBinding,
        private val itemClick: (BleDeviceBean) -> Unit
    ) : RecyclerView.ViewHolder(binding.root) {
        @SuppressLint("SetTextI18n")
        fun bind(bleDevice: BleDeviceBean, position: Int) {
            binding.tvIndex.text = "${position + 1}#"
            setSelectBg(bleDevice)

            binding.root.setOnClickListener {
                dataList.forEach { it.isSelect = false }
                bleDevice.isSelect = true
                notifyDataSetChanged()
            }
        }
        private fun setSelectBg(device: BleDeviceBean) {
            val bgRes = if (device.isSelect) R.drawable.shape_co_16_so_f2f6ff_st_1f39ff else R.drawable.shape_co_16_so_f7f7f7
            binding.root.setBackgroundResource(bgRes)
            if (device.isSelect){
                itemClick(device)
            }
        }
    }
}